//*********************************************************
//
//    Copyright (c) Microsoft. All rights reserved.
//    This code is licensed under the Apache License, Version 2.0.
//    THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
//    ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
//    IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
//    PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************

namespace Microsoft.Research.ScientificWorkflow.UIDesigner.Monitor
{
    using System;
    using System.Linq;
    using System.Windows.Forms.Integration;
    using Microsoft.Research.eResearch.Blackboard.Common;
    using Microsoft.Research.ScientificWorkflow.TridentUtilities;

    public class PerformanceCounterviewModel : IDisposable
    {
        private ChartPage chartControl = new ChartPage();

        private DateTime time;

        public string Concept { get; set; }

        public string Name { get; set; }

        public System.Windows.Forms.UserControl View
        {
            get { return this.chartControl; }
            protected set { this.chartControl = value as ChartPage; }
        }

        public PerformanceCounterviewModel(string concept, string name, string labelXAxis, string labelYAxis)
        {
            this.Concept = concept;
            this.Name = name;
            this.time = DateTime.Now;
            this.chartControl.XAxisLabel = labelXAxis;
            this.chartControl.YAxisLabel = labelYAxis;
        }

        public virtual void ProcessMessage(BlackboardMessage message)
        {
            double yvalue, xvalue;
            DateTime messageTime;

            if (!DateTime.TryParse(message["trident:EventTimestamp"], out messageTime))
            {
                messageTime = DateTime.Now;
            }

            xvalue = (int)((messageTime - this.time).TotalSeconds);

            if (!double.TryParse(message[Concept], out yvalue))
            {
                yvalue = 0;
            }

            this.chartControl.AddPointToLine(message["trident:ActivityName"], xvalue, yvalue);
        }

        public void ClearChart()
        {
            this.time = DateTime.Now;
            this.chartControl.ClearChart();
        }

        #region IDisposable Members

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        // The bulk of the clean-up code is implemented in Dispose(bool)
        protected virtual void Dispose(bool disposing)
        {
            if (disposing)
            {
                if (this.chartControl != null)
                {
                    this.chartControl.Dispose();
                }
            }
        }

        #endregion
    }
}
